//
//  testTheResult.cpp
//  MyTryForMapping2
//
//  Created by Артемий Соболев on 24.05.12.
//  Copyright (c) 2012 avriy@me.com. All rights reserved.
//

#include "testTheResult.h"


class checker {
public:
    checker(){
        numberToCompare = NULL;
    }
    bool checkLite(int fd){
        char buf[buffersiz];
        int end = lseek(fd, 0, SEEK_END);
        lseek(fd, 0, SEEK_SET);
        read(fd, buf, end);
        int i = 0;
        do i++; while (buf[i]!=',');
        if (atoi(&buf[i+1]) < numberToCompare) return false; 
        else numberToCompare = atoi(&buf[i+1]);
        i = end/2;
        do i++; while (buf[i]!=',');
        if (atoi(&buf[i+1]) < numberToCompare) return false; 
        else numberToCompare = atoi(&buf[i+1]);
        return true;
    }
    bool checkHard(int fd){
        char buf[buffersiz];
        int end = lseek(fd, 0, SEEK_END);
        lseek(fd, 0, SEEK_SET);
        read(fd, buf, end);
        int i = 0;
        while (i<end) {
        do i++; while (buf[i]!=',');
            if (atoi(&buf[i+1]) < numberToCompare) {
                return false; 
                
            }
            else numberToCompare = atoi(&buf[i+1]);
            i++;
        }
        return true;
    }
private:
    int numberToCompare;
};






bool dadyChecker(char name[],char mode[]){
    Iterator *iter = new Iterator(name);
    checker *cheksy = new checker();
    bool modeIsHard;
    if (strncmp("Hard", mode, 5*sizeof(char))==0) modeIsHard = true;
    else modeIsHard = false;
    
    do if(!cheksy->checkLite(iter->next())) {
        iter->~Iterator();
        return false;
    }
    while (iter->haveNext());
    iter->~Iterator();
    
    if (modeIsHard){        
        do if(!cheksy->checkHard(iter->next())) {
            iter->~Iterator();
            return false;   
        }
        while (iter->haveNext());
        iter->~Iterator();
    }
    return true;
    
}


int main (int argc, char *argv[])
{
    char *fileName;
    char *mode;
    char defaultName[] = "in.csv";
    char defaultMode[] = "Soft";
    if (argc > 1) fileName = argv[1];
    else fileName = defaultName;
    if (argc > 2) mode = argv[2];
    else mode = defaultMode;
    if (dadyChecker(fileName, mode)) {
        printf("cool,it's fine!\n");
        return 1;
    }
    else {
        printf("not sorted\n");
        return 0;
    }
}